package com.may.wind.service;

import com.may.wind.dao.RoleMenuRepository;
import com.may.wind.entity.RoleMenu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class RoleMenuService {
    @Autowired
    RoleMenuRepository roleMenuRepository;

    public List<RoleMenu> findAllByRoleId(long roleId) {
        return roleMenuRepository.findAllByRoleId(roleId);
    }

    public List<RoleMenu> findAllByRoleId(List<Long> roleIds) {
        return roleMenuRepository.findAllByRoleIdIn(roleIds);
    }

    public void save(RoleMenu roleMenu) {
        roleMenuRepository.save(roleMenu);
    }

    @Modifying
    @Transactional
    public void updateRoleMenu(long roleId, Map<String, List<Long>> menuIds) {
        roleMenuRepository.deleteAllByRoleId(roleId);
        List<RoleMenu> roleMenus = new ArrayList<>();
        for (long menuId : menuIds.get("menusIds")) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setMenuId(menuId);
            roleMenu.setRoleId(roleId);
            roleMenus.add(roleMenu);
        }

        roleMenuRepository.saveAll(roleMenus);
    }
}
